package com.acme.team03.net;

import java.io.IOException;

import com.acme.team03.commands.Command;
import com.acme.team03.history.ChatHistory;
import com.acme.team03.messages.Message;
import com.acme.team03.messages.TextMessage;
import com.acme.team03.net.server.ConnectionDispatcher;

public final class ServerMessageHandler extends MessageHandler {
	
	ChatHistory chatHistory = new ChatHistory();

	public ServerMessageHandler(ConnectionDispatcher connDispatcher) {
		super(connDispatcher);
	}

	protected void processMessage(Message msg) {
		TextMessage textMsg = (TextMessage) msg;
		System.out.println("[RCVD CLIENT MESSAGE] " + textMsg.getText());
		if (textMsg.getText().equals("Hist")) {
			for (Connection connection: connDispatcher.getAllConnections()) {
				if (msg.getProperty("ID").equals(connection.getID())) {
					StringBuilder sbHistory = new StringBuilder();
					for (Message message : chatHistory.getMessages()) {
						sbHistory.append(message.getProperty("Date") + ">" +  ((TextMessage) message).getText() + "\n");
					}
					try {
						TextMessage tmessage = new TextMessage(sbHistory.toString());
						tmessage.setProperty("history", true);
						connection.sendMessage(tmessage);
					} catch (IOException e) {
						e.printStackTrace();
					}
					return;
				}
			}
		}
		chatHistory.addMessage(msg);
//		chatHistory.persist();
		Command sendMsgCommand = new SendMessageCommand(textMsg, connDispatcher);
		sendMsgCommand.execute();
	}

}
